<?php

namespace app\controllers;

use Yii;
use app\components\Oauth2Controller as Controller;

class Oauth2Controller extends Controller{

    public function actionIndex(){
        return $this->render('index');
    }

    public function actionToken(){
        $this->server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

    public function actionAuthorize(){

        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();

        if(!$this->server->validateAuthorizeRequest($request, $response)) {
            $response->send();
            die;
        }

        $is_authorized = ($_POST['authorized'] === 'yes');

        $this->server->handleAuthorizeRequest($request, $response, $is_authorized);

        if($is_authorized) {

            // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client

            $code= substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);

//            exit("SUCCESS! Authorization Code: $code");

            exit(json_encode(["code"=>1, "info"=>"success", "AuthorizationCode"=>$code]));

        }

        $response->send();
    }

}
